package com.example.agriapp.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import com.example.agriapp.R;
import com.example.agriapp.data.AgriDatabaseHelper;

public class RegisterActivity extends AppCompatActivity {
    private EditText etUsername, etPassword, etRealName, etPhone;
    private Button btnRegister;
    private ImageView ivBack;
    private AgriDatabaseHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
//        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.bottom_nav_icon_selected));
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.bottom_nav_icon_selected));
        dbHelper = new AgriDatabaseHelper(this);

        etUsername = findViewById(R.id.et_name);
        etPassword = findViewById(R.id.et_password);
        etRealName = findViewById(R.id.et_user_name);
        etPhone = findViewById(R.id.et_phone);
        btnRegister = findViewById(R.id.btn_register);
        ivBack = findViewById(R.id.iv_back);

        btnRegister.setOnClickListener(v -> registerUser());
        ivBack.setOnClickListener(v -> onBackPressed());
    }

    private void registerUser() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String realName = etRealName.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();

        if (username.isEmpty() || password.isEmpty() || realName.isEmpty() || phone.isEmpty()) {
            Toast.makeText(this, "请填写所有字段", Toast.LENGTH_SHORT).show();
            return;
        }

        if (username.equals("admin")){
            Toast.makeText(this, "用户名不能为admin", Toast.LENGTH_SHORT).show();
            return;
        }
        if (dbHelper.isUserExists(username)) {
            Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show();
            return;
        }

        if (dbHelper.registerUser(username, password, realName, phone)) {
            Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
            intent.putExtra("USERNAME", username);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "注册失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        dbHelper.close();
        super.onDestroy();
    }
}
